package com.shxc.smarttrade.old.activity;

import android.Manifest;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.just.library.AgentWeb;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.utils.Arith;
import com.shxc.smarttrade.old.utils.ButtonUtils;
import com.shxc.smarttrade.old.utils.QRCode;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.lang.ref.WeakReference;

import butterknife.BindView;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * Created by jcdev1 on 2017/5/12.
 */

public class InvateFriendActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.rl_left)
    RelativeLayout rlLeft;
    @BindView(R.id.btn_share_code)
    Button btnShareCode;
    @BindView(R.id.btn_share_url)
    Button btnShareUrl;
    @BindView(R.id.ll_webview)
    LinearLayout llWebView;

    private AgentWeb mAgentWeb;
    private UMShareListener mShareListener;
    private ShareAction mShareActionUrl;
    private ShareAction mShareActionCode;

    private boolean shareAble = true;//是否可以分享
    private int whatBtn = 0;//0：分享链接 1：分享二维码
    private static String SHAREURL = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invate_friend);
        initView();
        initListener();
    }

    /**
     * 初始化View
     */
    private void initView() {
        SHAREURL = "http://m.mayiforex.com/m/invitation/index.html?telephone=" + SpUtils.getString(this, "telephone", "");
        UMShareAPI.get(this);
        String webUrl = "http://m.mayiforex.com/m/invitation/detail.html?isClient=1&accessToken=" + SpUtils.getString(this, "accessToken", "") + "&userId=" + SpUtils.getInt(this, "userId");

        tvCenter.setText("邀请好友");
        mAgentWeb = AgentWeb.with(this)//传入Activity
                .setAgentWebParent(llWebView, new LinearLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams
                .useDefaultIndicator()// 使用默认进度条
                .defaultProgressBarColor() // 使用默认进度条颜色
//                .setReceivedTitleCallback(mCallback) //setting Web 页面的 title 回调
                .createAgentWeb()//
                .ready()
                .go(webUrl);

        //发送图片
        Bitmap bmp1 = BitmapFactory.decodeResource(getResources(), R.mipmap.share_bg);
        Bitmap bmp2 = QRCode.createQRCodeWithLogo(SHAREURL, BitmapFactory.decodeResource(getResources(), R.mipmap.share_logo));
        Bitmap bmp3 = mergeBitmap(bmp1, bmp2);
        if (bmp2 == null || bmp3 == null)
            shareAble = false;
        UMImage image = new UMImage(this, bmp3);

        //发送链接
        UMWeb web = new UMWeb(SHAREURL);
        web.setTitle("好友送您$200体验金！");
        web.setDescription("快来和我一起，赢1000美元现金。");
        web.setThumb(new UMImage(InvateFriendActivity.this, R.drawable.share_logo2));

        mShareListener = new CustomShareListener(this);

        //分享链接
        mShareActionUrl = new ShareAction(InvateFriendActivity.this).setDisplayList(
                SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE)
                .withMedia(web)
                .setCallback(mShareListener);
        //分享二维码
        mShareActionCode = new ShareAction(InvateFriendActivity.this).setDisplayList(
                SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE)
                .withMedia(image)
                .setCallback(mShareListener);


    }

//    private WebChromeClient webChromeClient = new WebChromeClient() {
//        @Override
//        public void onProgressChanged(WebView view, int newProgress) {
//            super.onProgressChanged(view, newProgress);
//            mAgentWeb.getJsEntraceAccess().quickCallJs("handleHideBottom");
//        }
//    };

    /**
     * 初始化监听器
     */
    private void initListener() {
        rlLeft.setOnClickListener(this);
        btnShareCode.setOnClickListener(this);
        btnShareUrl.setOnClickListener(this);
    }

    private void showShare() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            if (shareAble) {
                if (whatBtn == 0)
                    mShareActionUrl.open();
                else
                    mShareActionCode.open();
            } else
                Toast.makeText(this, "分享失败", Toast.LENGTH_SHORT).show();

        } else {
            PermissionGen.with(InvateFriendActivity.this)
                    .addRequestCode(100)
                    .permissions(
                            Manifest.permission.READ_EXTERNAL_STORAGE)
                    .request();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /**
     * 成功获取权限
     */
    @PermissionSuccess(requestCode = 100)
    public void doSomething() {
        if (shareAble) {
            if (whatBtn == 0)
                mShareActionUrl.open();
            else
                mShareActionCode.open();
        } else
            Toast.makeText(this, "分享失败", Toast.LENGTH_SHORT).show();
    }

    /**
     * 获取权限失败
     */
    @PermissionFail(requestCode = 100)
    public void doFailSomething() {
        Toast.makeText(this, "获取权限失败 请到设置中打开", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_left:
                if (mAgentWeb.getWebCreator().get().canGoBack()) {
                    mAgentWeb.back();
                } else {
                    finish();
                }
                break;
            case R.id.btn_share_url:
                whatBtn = 0;
                if (!ButtonUtils.isFastDoubleClick(R.id.btn_share_code, 1500)) {
                    showShare();
                }
                break;
            case R.id.btn_share_code:
                whatBtn = 1;
                if (!ButtonUtils.isFastDoubleClick(R.id.btn_share_code, 1500)) {
                    showShare();
                }
                break;

        }
    }


    /**
     * 分享结果回调
     */
    private static class CustomShareListener implements UMShareListener {

        private WeakReference<InvateFriendActivity> mActivity;

        private CustomShareListener(InvateFriendActivity activity) {
            mActivity = new WeakReference(activity);
        }

        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(mActivity.get(), "分享成功", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(mActivity.get(), "分享失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(mActivity.get(), "分享取消", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 屏幕横竖屏切换时避免出现window leak的问题
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mShareActionUrl.close();
        mShareActionCode.close();
    }

    /**
     * 把两个位图覆盖合成为一个位图，以底层位图的长宽为基准
     *
     * @param backBitmap  在底部的位图
     * @param frontBitmap 盖在上面的位图
     * @return
     */
    public static Bitmap mergeBitmap(Bitmap backBitmap, Bitmap frontBitmap) {

        if (backBitmap == null || backBitmap.isRecycled()
                || frontBitmap == null || frontBitmap.isRecycled()) {
            return null;
        }
        try {
            Bitmap bitmap = backBitmap.copy(Bitmap.Config.ARGB_8888, true);
            double bmWidth = bitmap.getWidth();
            double bmHght = bitmap.getHeight();
            Point point1 = new Point();
            Point point2 = new Point();
            point1.x = (int) Arith.mul(238, Arith.div(bmWidth, 750));
            point1.y = (int) Arith.mul(758, Arith.div(bmHght, 1334));
            point2.x = (int) Arith.mul(515, Arith.div(bmWidth, 750));
            point2.y = (int) Arith.mul(1035, Arith.div(bmHght, 1334));
            Canvas canvas = new Canvas(bitmap);
            Rect baseRect = new Rect(point1.x, point1.y, point2.x, point2.y);//该矩形区域为图片展示的位置和范围，起点坐标（0，0）在左上角
            Rect frontRect = new Rect(0, 0, frontBitmap.getWidth(), frontBitmap.getHeight());
            canvas.drawBitmap(frontBitmap, frontRect, baseRect, null);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mAgentWeb.clearWebCache();
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroy();
        System.gc();
    }
}
